package com.jinmdz.fmis.common.util.third;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.util.List;

/**
 * gson工具类
 *
 * @author LiCongLu
 * @date 2019-12-19 11:55
 */
public class GsonUtil {
    /**
     * 日期格式化
     */
    private static final String PATTERN = "yyyy-MM-dd HH:mm:ss";

    private static Gson instance;

    private GsonUtil() {
    }

    public static Gson getInstance() {
        if (instance == null) {
            synchronized (GsonUtil.class) {
                if (instance == null) {
                    instance = new GsonBuilder()
                            .setDateFormat(PATTERN)
                            .create();
                }
            }
        }
        return instance;
    }

    /**
     * 转字符串
     *
     * @param src
     * @return
     */
    public static String toJson(Object src) {
        try {
            return getInstance().toJson(src);
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 转实体
     */
    public static <T> T fromJson(String json, Class<T> classOfT) {
        try {
            return getInstance().fromJson(json, classOfT);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 转成list
     * (不好用，仅仅做参考)
     *
     * @param json
     * @param classOfT
     * @return
     */
    private static <T> List<T> toList(String json, Class<T> classOfT) {
        try {
            return getInstance().fromJson(json,
                    new TypeToken<List<T>>() {
                    }.getType());
        } catch (Exception e) {
            return null;
        }
    }
}
